package org.biojava.services.das.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.zip.GZIPOutputStream;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import org.biojava.das.ucsc.UCSCtoDAS1Sources;
import org.biojava.dasobert.dasregistry.Das1Source;
import org.biojava.dasobert.dasregistry.DasSource;
import org.biojava.dasobert.dasregistry.DasSourceFilter;
import org.biojava.services.das2.Das1SourceDbProvider;


public class UCSCServlet extends HttpServlet{
	UCSCtoDAS1Sources ucscConverter;
	private boolean gzipEncoding = true;
	public UCSCServlet() {
		super();

	}

	public void init(ServletConfig config)
	throws ServletException
	{
		super.init(config);
		System.out.println("init das2 servlet again!!");
		ucscConverter=new UCSCtoDAS1Sources();


	}
	
	public void doGet(
			HttpServletRequest req,
			HttpServletResponse resp
	)
	throws ServletException, IOException
	{
		 System.out.println("got a get >" + req.getPathInfo()+"< " + req.getQueryString() + " | " +
                " | " + req.getRequestURI() + 
                  " | " + req.getPathTranslated() + " | " + req.getContextPath() + " | " + req.getHeaderNames());

		 
		// see dazzle
		String encodingStr = req.getHeader("Accept-Encoding");
		if (encodingStr != null && gzipEncoding)  {
			if (encodingStr.indexOf("gzip") != -1) {
				resp = new HttpServletResponseWrapper(resp) {
					GZIPOutputStream gzipOut = null;
					public PrintWriter getWriter() throws IOException {
						gzipOut = new GZIPOutputStream(getResponse().getOutputStream());
						return new PrintWriter(gzipOut) {
							// we return a subclassed PrintWriter which finishes GZIPOutputStream when close is called
							public void close() {
								super.close();
								try {
									gzipOut.finish();
								}
								catch (IOException ie) {
									System.err.println("Unexpected IOException when closing GZIPOutputStream");
								}
							}
						};
					}
				};
				resp.setHeader("Content-Encoding", "gzip");
			}
		}

		String cmdPath = req.getPathInfo();
		if (cmdPath == null) {
			cmdPath = "";
		}
		//System.out.println("commandPath " + cmdPath);

		StringTokenizer toke = new StringTokenizer(cmdPath, "/");
		

		List nameComponents = new ArrayList();
		String command = toke.nextToken();
		// System.out.println("got command " + command);




		boolean responded = false;
		try {
			System.out.println("got command >" + command + "<");

			 if (command.equals("sources")) {

                // get all DAS sources with label ...
                String label      = req.getParameter("label");
                String organism   = req.getParameter("organism");
                String authority  = req.getParameter("authority");
                String capability = req.getParameter("capability");
                String type       = req.getParameter("type");
                
                displayDas1Sources(req,
						resp,
						label,
						organism,
						authority,
						capability,
						type); 
				responded = true;
			 }else if (command.startsWith("DS_") || (toke.countTokens()==0 && !command.equals("sources"))) {
					System.out.println("got das single source command="+command);
					
						displaySingleDas1Source(req, resp, command);
						responded = true;
					

					// beyond this point we need to account for search option and
					// filter by searching first
				}
		} catch (Exception e ){
			//sendError()
			e.printStackTrace();
		}

		//resp.getOutputStream().flush();

	}

	private void displayDas1Sources(HttpServletRequest req,
			HttpServletResponse resp, String label, String organism,
			String authority, String capability, String type) {
		
		
		List dsns=ucscConverter.getDSNs();
		List<DasSource>sources=ucscConverter.getDas1Sources(dsns);
		
		/*System.out.println("got #sources " + sources.length + 
        		" filtering by label " + label +
        		" org " + organism +
        		" authority " + authority +
        		" capability " + capability +
        		" type " + type);
		 */
		//DasSourceFilter filter = new DasSourceFilter();
		//sources = filter.filterBy(sources,label,organism,authority,capability,type);
		//System.out.println("got #source after filter: " + sources.length);

		ServletResponseWriter writer = new ServletResponseWriter();
		try {
			writer.writeResponse(resp,sources,sources.size(), 0, 0, false);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void displaySingleDas1Source(HttpServletRequest req,
			HttpServletResponse resp, String dasSourceId)
			throws ServletException, IOException {

		DasSource source = ucscConverter.getSingleDasSource(dasSourceId);
		List<DasSource> sources = new ArrayList();
		sources.add(source);
		ServletResponseWriter writer = new ServletResponseWriter();
		writer.writeResponse(resp, sources, 0, 0, 0, false);
	}
}
